//
//  SearchViewController.m
//  quanminzhekou
//
//  Created by zxl on 15/1/7.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "SearchViewController.h"
#import "CustomTableViewController.h"
#import "CommonEngine.h"
#import "CommonCellViewModel.h"
#import "SearchCell.h"

#define SearchHistory @"search_history"

@interface SearchViewController ()
@property (nonatomic) NSMutableArray* searchHistoryArr;
@property (nonatomic) MKNetworkOperation* searchOperation;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchHistoryArr = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:SearchHistory]];
    if (nil == _searchHistoryArr) {
        _searchHistoryArr = [[NSMutableArray alloc] init];
    }
}

- (void)dealloc
{
    [self.searchOperation cancel];
}

#pragma mark -
- (void)getSearchResultDataWith:(NSString*)searchKey {
    if ([_searchOperation isExecuting]) {
        return;
    }
    
    NSString* kw = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)searchKey,NULL,CFSTR("!*'();:@&=+$,/?%#[]"),kCFStringEncodingUTF8));
    NSString* path = [[CommonEngine sharedInstance] urlPathForSearchWithDictionary:@{@"kw": kw}];
    
    __weak typeof(self) weakSelf = self;
    _searchOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
        NSNumber* status = [result objectForKey:@"status"];
        NSNumber* count = [result objectForKey:@"count"];
        if (1 == status.integerValue) {
            if (0 != count.integerValue) {
                NSMutableArray* resArr = [[NSMutableArray alloc] init];
                NSArray* arr = [result objectForKey:@"res"];
                for (NSDictionary* dic in arr) {
                    CommonCellModel* model = [[CommonCellModel alloc] initWithDic:dic];
                    CommonCellViewModel* viewModel = [[CommonCellViewModel alloc] initWithCommonCellModel:model];
                    [resArr addObject:viewModel];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf saveSearchKeyWord:searchKey andShowCustomTableViewWithDataArr:resArr];
                });
                
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"暂无您的搜索结果~" message:@"请更换搜索词！" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
                    [alert show];
                });
            }
        }
    } errorHandler:^(NSError *errMsg) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"网络错误！" message:[NSString stringWithFormat:@"%@", errMsg.localizedDescription] delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alert show];
    }];
}

- (void)saveSearchKeyWord:(NSString*)keyWord andShowCustomTableViewWithDataArr:(NSMutableArray*)dataArr {
    NSString* text = [keyWord stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([self.searchHistoryArr containsObject:text]) {
        [self.searchHistoryArr removeObject:text];
    }
    [self.searchHistoryArr insertObject:text atIndex:0];
    [[NSUserDefaults standardUserDefaults] setObject:self.searchHistoryArr forKey:SearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.tableView reloadData];
    
    CustomTableViewController* controller = [self.storyboard instantiateViewControllerWithIdentifier:@"CustomTableViewController"];
    controller.title = text;
    controller.keyword = text;
    controller.customDataArr = dataArr;
    controller.type = CustomTableViewControllerTypeSearch;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - IBAction
- (IBAction)onTapCancelBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onTapClearSearchHistoryBtn:(id)sender {
    [_searchHistoryArr removeAllObjects];
    [[NSUserDefaults standardUserDefaults] setObject:self.searchHistoryArr forKey:SearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.tableView reloadData];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (![textField.text isKindOfClass:[NSString class]] || 0 == textField.text.length) {
        return NO;
    }
    
    [textField resignFirstResponder];
    
    [self getSearchResultDataWith:textField.text];
    
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchHistoryArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchCell *cell = (SearchCell*)[tableView dequeueReusableCellWithIdentifier:@"SearchCell"];
    
    cell.titleLab.text = [self.searchHistoryArr objectAtIndex:indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString* string = [self.searchHistoryArr objectAtIndex:indexPath.row];
    
    [self getSearchResultDataWith:string];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.textField resignFirstResponder];
}

@end
